import request from '../../utils/request';
import config from '../../config';
Page({
    data: {
        taskId: null,
        statusBarHeight: wx.getSystemInfoSync().statusBarHeight,
        navBarHeight: wx.getSystemInfoSync().platform === 'ios' ? 44 : 48,
        mediaList: [], // 存储选择的图片或视频 { type: 'image'/'video', tempFilePath: '...', uploadProgress: 0, thumbTempFilePath: '...'(for video) }
        maxFiles: 4,
        uploadIcon: '/assets/images/add_image.png', // 上传按钮的加号图标，你需要准备这个图标
        isUploading: false, // 新增：全局上传状态标记
        showFullscreenVideo: false, // 新增：是否显示全屏视频播放器
        currentVideoSrc: '' // 新增：当前播放的视频链接
    },

    onLoad: function (options) {
        this.setData({
            taskId: options.taskId || null
        });
        console.log('Submit task for taskId:', this.data.taskId);
        // 你可能需要在这里获取更精确的导航栏高度
        // const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
        // this.setData({
        //   navBarHeight: menuButtonInfo.height + (menuButtonInfo.top - this.data.statusBarHeight) * 2
        // });
    },


    // 选择图片或视频
    chooseMedia: function () {
        if (this.data.mediaList.length >= this.data.maxFiles) {
            wx.showToast({
                title: `最多上传${this.data.maxFiles}个文件`,
                icon: 'none'
            });
            return;
        }

        wx.chooseMedia({
            count: this.data.maxFiles - this.data.mediaList.length,
            mediaType: ['image', 'video'], // 同时允许图片和视频
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            maxDuration: 60, // 视频最长拍摄时间，单位秒
            camera: 'back',
            success: (res) => {
                console.log('ChooseMedia success:', res);
                const newMedia = res.tempFiles.map(file => ({
                    type: res.type, // chooseMedia 返回的 type 是 'video' 或 'image'
                    tempFilePath: file.tempFilePath,
                    thumbTempFilePath: file.thumbTempFilePath, // 视频的封面图
                    size: file.size,
                    uploadProgress: 0 // 新增：初始化上传进度
                }));
                this.setData({
                    mediaList: this.data.mediaList.concat(newMedia)
                });
            },
            fail: (err) => {
                console.log('ChooseMedia fail:', err);
                if (err.errMsg !== "chooseMedia:fail cancel") {
                    wx.showToast({
                        title: '选择失败',
                        icon: 'none'
                    });
                }
            }
        });
    },

    // 预览图片或视频
    previewMedia: function (e) {
        const index = e.currentTarget.dataset.index;
        const currentMedia = this.data.mediaList[index];

        if (currentMedia.type === 'image') {
            wx.previewImage({
                current: currentMedia.tempFilePath,
                urls: this.data.mediaList.filter(item => item.type === 'image').map(item => item.tempFilePath)
            });
        } else if (currentMedia.type === 'video') {
            // 微信小程序没有直接的视频预览API，通常点击后跳转到带<video>组件的页面播放
            // 或者，如果只是简单播放，可以考虑使用 wx.createVideoContext在一个弹窗中播放
            // 这里简单地打印日志，你可以根据需求实现具体的预览逻辑
            console.log('Preview video:', currentMedia.tempFilePath);
            this.setData({
                currentVideoSrc: currentMedia.tempFilePath,
                showFullscreenVideo: true
            }, () => {
                const videoContext = wx.createVideoContext('fullscreenVideoPlayer', this);
                videoContext.requestFullScreen({
                    direction: 0
                }); // 0表示正常竖屏，90表示横屏
                videoContext.play();
            });
        }
    },

    // 视频全屏状态改变
    onVideoFullscreenChange: function (e) {
        console.log('Video fullscreen change', e.detail);
        // 当退出全屏时，隐藏 video 组件
        if (!e.detail.fullScreen) {
            this.setData({
                showFullscreenVideo: false,
                currentVideoSrc: '' // 清空 src，防止背景播放
            });
        }
    },

    // 视频播放结束或用户手动关闭（某些机型退出全屏也会触发ended）
    onVideoEndedOrClose: function () {
        this.setData({
            showFullscreenVideo: false,
            currentVideoSrc: ''
        });
    },

    // 视频播放错误
    onVideoError: function (e) {
        console.error('Video Error:', e.detail.errMsg);
        wx.showToast({
            title: '视频播放失败',
            icon: 'none'
        });
        this.setData({
            showFullscreenVideo: false,
            currentVideoSrc: ''
        });
    },

    // 删除已选的媒体文件
    deleteMedia: function (e) {
        const index = e.currentTarget.dataset.index;
        const newList = [...this.data.mediaList];
        newList.splice(index, 1);
        this.setData({
            mediaList: newList
        });
    },

    uploadFile: function (file, index) {
        return new Promise((resolve, reject) => {
            const uploadTask = wx.uploadFile({
                url: config.BASE_URL + 'api/login/upload',
                fileType: 'image',
                filePath: file.tempFilePath,
                name: 'file',
                header: {
                    'Authorization': 'tf: ' + wx.getStorageSync('token')
                },
                success: (res) => {
                    let data = JSON.parse(res.data);
                    if (data.code == 200) {
                        if (data.data && typeof data.data.url === 'string') {
                            const mediaList = this.data.mediaList;
                            if (mediaList[index]) {
                                mediaList[index].uploadProgress = 100;
                                this.setData({
                                    mediaList
                                });
                            }
                            resolve(data.data.url);
                        } else {
                            console.error('Upload success but response format error: data.data or data.data.url is missing.', data);
                            wx.showToast({
                                title: '上传成功但响应格式错误',
                                icon: 'none'
                            });
                            reject('上传成功但响应格式错误');
                        }
                    } else {
                        wx.showToast({
                            title: data.message || '上传失败',
                            icon: 'none'
                        });
                        reject(data.message || '上传失败');
                    }
                },
                fail: (error) => {
                    wx.showToast({
                        title: '上传请求失败',
                        icon: 'none'
                    });
                    reject(error);
                }
            });

            uploadTask.onProgressUpdate((res) => {
                const mediaList = this.data.mediaList;
                if (mediaList[index]) {
                    mediaList[index].uploadProgress = res.progress;
                    this.setData({
                        mediaList
                    });
                }
            });
        });
    },

    // 确认提交
    handleConfirmSubmit: function () {
        if (this.data.mediaList.length === 0) {
            wx.showToast({
                title: '请至少上传一个文件',
                icon: 'none'
            });
            return;
        }

        if (this.data.isUploading) { // 防止重复提交
            wx.showToast({
                title: '正在上传中...',
                icon: 'none'
            });
            return;
        }

        this.setData({
            isUploading: true
        }); // 开始上传，设置标记
        wx.showLoading({
            title: '提交中...',
            mask: true
        });

        // 在这里实现文件上传逻辑
        // 你需要遍历 this.data.mediaList，对每个文件调用 wx.uploadFile
        // 将所有文件上传成功后，再调用后端接口提交任务凭证信息
        let uploadPromises = this.data.mediaList.map((file, index) => this.uploadFile(file, index));
        Promise.all(uploadPromises).then(urls => {
            console.log('All files uploaded successfully:', urls);
            // 调用后端接口提交任务凭证信息
            this.submitTask(urls);
        }).catch(error => {
            console.error('Error uploading files:', error);
            wx.hideLoading(); // 确保出错时也隐藏 loading
            this.setData({
                isUploading: false
            }); // 上传失败，重置标记
            wx.showToast({
                title: '部分文件上传失败，请重试',
                icon: 'none'
            });
        });
    },
    submitTask: function (urls) {
        let data = {
            taskId: this.data.taskId,
            taskImageList: urls.map(url => ({
                url: url,
            })),
            userId: wx.getStorageSync('userInfo').id
        }
        request({
            url: 'api/home/submitTask',
            method: 'POST',
            data: data
        }).then(res => {
            wx.showToast({
                title: '提交成功',
                icon: 'success'
            });
            setTimeout(() => {
                wx.switchTab({
                    url: '/pages/index/index'
                });
            }, 1500);
        }).catch(error => {
            wx.hideLoading(); // 确保提交完成后隐藏 loading
            console.log('Submit task fail:', error);
        }).finally(() => {
            this.setData({
                isUploading: false
            }); // 提交完成，重置标记
        });
    }

});